﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Chameleon.Samples.Wpf
{
	using Chameleon.Data;
	using System.Configuration;

	/// <summary>
	/// This is code is for demonstrating capability; it is not indicative of good UI design.
	/// </summary>
	
	public partial class MainWindow : Window
	{
		/// <summary>
		/// Gets the currently selected provider.
		/// </summary>
		
		Func<IDepository> SelectedProvider { get { return ProviderSelector.SelectedValue as Func<IDepository>; } }


		/// <summary>
		/// Returns all currently selected entities.
		/// </summary>

		IEnumerable<BasicEntity> SelectedEntities { get { return EntityGrid.SelectedItems.OfType<BasicEntity>(); } }


		/// <summary>
		/// Binds the data grid to all items currently in the database.
		/// </summary>
		
		void ListItems()
		{
			using ( var db = SelectedProvider() )
				EntityGrid.ItemsSource = BasicEntity.All( db );
		}


		/// <summary>
		/// Removes the specified items from the database.
		/// </summary>

		void DeleteItems()
		{
			var provider = SelectedProvider;

			if ( provider != null )
			{
				using ( var db = provider() )
					BasicEntity.Delete( db, SelectedEntities );

				ListItems();
			}
		}


		/// <summary>
		/// Inserts a new item into the database.
		/// </summary>

		void InsertItem()
		{
			var provider = SelectedProvider;

			if ( provider != null )
			{
				using ( var db = provider() )
					BasicEntity.Insert( db );

				ListItems();
			}
		}


		/// <summary>
		/// Updates the selected items in the database.
		/// </summary>

		void UpdateItems()
		{
			var provider = SelectedProvider;

			if ( provider != null )
			{
				using ( var db = provider() )
					BasicEntity.Update( db, SelectedEntities );

				ListItems();
			}
		}


		public MainWindow()
		{
			InitializeComponent();

			// add all possible providers to the selector
			ProviderSelector.ItemsSource = new Dictionary<string,Func<IDepository>>()
			{
				 { "Entity Framework", ()=>EntityContext.Depository() }
				,{ "Linq to SQL", ()=> SqlContext.Depository() }
			};

			// set selection changed event
			ProviderSelector.SelectionChanged += (o,e) => ListItems();
			InsertButton.Click += (o,e) => InsertItem();
			DeleteButton.Click += (o,e) => DeleteItems();
			UpdateButton.Click += (o,e) => UpdateItems();
		}
	}
}
